package elitech.vietnam.myfashion.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Paint;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.myfashion.LoginActivity;
import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.config.Const;
import elitech.vietnam.myfashion.dialog.ExchangeDialog;
import elitech.vietnam.myfashion.dialog.ShippingDialog;
import elitech.vietnam.myfashion.dialog.WarningDialog;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Color;
import elitech.vietnam.myfashion.entites.Order;
import elitech.vietnam.myfashion.entites.OrderDetail;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.entites.Size;
import elitech.vietnam.myfashion.extend.AsyncTask;
import elitech.vietnam.myfashion.utilities.Utilities;

public class HeaderDetailView extends LinearLayout implements OnClickListener {

	private MainActivity		mContext;
	private LinearLayout		mLayoutColor, mLayoutSize;
	private Button				mBtnBuy, mBtnAdd;
	private ImageView			mImage;
	private TextView			mTxtName, mTxtPrice, mTxtSaleOff, mTxtContent, mTxtHowto, mTxtReview;
	private EditText			mEdQuantity;
	private ArrayList<String>	mColorNameList	= new ArrayList<String>();
	private ArrayList<String>	mSizeNameList	= new ArrayList<String>();
	private ArrayList<Color>	mColorList		= new ArrayList<Color>();
	private ArrayList<Size>		mSizeList		= new ArrayList<Size>();
	private Spinner				mSpinColor, mSpinSize;
	private ArrayAdapter<String>	mAdapterColor, mAdapterSize;

	private boolean					isAdding	= false;
	private boolean					isLoading	= false;
	private Product					mProduct;
	private ExchangeDialog			mDialog;

	public HeaderDetailView(MainActivity context, Product product) {
		super(context);
		this.mContext = context;
		this.mProduct = product;

		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if (inflater != null) {
			inflater.inflate(R.layout.headerdetail, this);
		}

		mImage = (ImageView) findViewById(R.id.detail_imgProduct);
		mTxtName = (TextView) findViewById(R.id.detail_txtCode);
		mTxtPrice = (TextView) findViewById(R.id.detail_txtPrice);
		mTxtContent = (TextView) findViewById(R.id.detail_txtContent);
		mTxtSaleOff = (TextView) findViewById(R.id.detail_txtSaleOff);
		mTxtHowto = (TextView) findViewById(R.id.detail_txtHowto);
		mTxtReview = (TextView) findViewById(R.id.detail_txtReview);
		mEdQuantity = (EditText) findViewById(R.id.detail_txtQuantity);

		mLayoutColor = (LinearLayout) findViewById(R.id.detail_layColor);
		mLayoutSize = (LinearLayout) findViewById(R.id.detail_laySize);
		mSpinColor = (Spinner) findViewById(R.id.detail_spinnerColor);
		mSpinSize = (Spinner) findViewById(R.id.detail_spinnerSize);
		mBtnBuy = (Button) findViewById(R.id.detail_btnBuy);
		mBtnAdd = (Button) findViewById(R.id.detail_btnAdd);

		mDialog = new ExchangeDialog(mContext);

		mTxtHowto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!mDialog.isShowing())
					mDialog.show();
			}
		});

		// mImage.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// Intent i = new Intent(mContext, ImageViewActivity.class);
		// i.putExtra("Link", mProduct.Image);
		// mContext.startActivity(i);
		// }
		// });

		UrlImageViewHelper.setUrlDrawable(mImage, Const.SERVER_IMAGE_THUMB_URL + mProduct.Image, R.drawable.loading300);

		mBtnBuy.setOnClickListener(this);
		mBtnAdd.setOnClickListener(this);
		mTxtReview.setOnClickListener(this);

		mAdapterColor = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, mColorNameList);
		mAdapterColor.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		mSpinColor.setAdapter(mAdapterColor);

		mAdapterSize = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, mSizeNameList);
		mAdapterSize.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		mSpinSize.setAdapter(mAdapterSize);

		mEdQuantity.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					checkQuantity();
				}
			}
		});

		mEdQuantity.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (!mEdQuantity.getText().toString().equals("")) {
					int count1 = Integer.parseInt(mEdQuantity.getText().toString());
					if (count1 > 10) {
						mEdQuantity.setText("");
						mEdQuantity.append("10");
					}
				}
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override
			public void afterTextChanged(Editable s) {}
		});

		mTxtName.setText(mProduct.Name);
		mTxtPrice.setText(Utilities.numberFormat(mProduct.PriceVN) + " VND");

		String content = "";
		if (mProduct.Content != null)
			content = mProduct.Content.replace("<br>", "\n");
//		mTxtContent.setText(content);
		mTxtContent.setGravity(Gravity.CENTER);

		if (mProduct.SaleOff > 0) {
			mTxtSaleOff.setText(Utilities.numberFormat(mProduct.PriceSale) + " VND");
			mTxtSaleOff.setVisibility(View.VISIBLE);
			mTxtPrice.setPaintFlags(mTxtPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
		}
		if (mProduct.ColorList.size() == 0)
			GetColor();
		else
			LoadColor();

		if (mProduct.SizeList.size() == 0)
			GetSize();
		else
			LoadSize();

	}

	private void GetSize() {
		new CallServiceTask() {
			private ArrayList<Size>	rs	= new ArrayList<Size>();

			public void work() {
				try {
					rs = service.getProductSize(mProduct.Id);
				} catch (IOException e) {} catch (XmlPullParserException e) {}
			};

			protected void onPostExecute(Void result) {
				mBtnBuy.setText(R.string.buyitnow);
				mBtnAdd.setText(R.string.addtocart);
				isLoading = false;
				mProduct.SizeList.addAll(rs);
				LoadSize();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void LoadSize() {
		if (mProduct.SizeList.size() != 0) {
			mSizeNameList.clear();
			mSizeList.clear();
			mSizeList.addAll(mProduct.SizeList);
			mSizeNameList.add("");
			for (Size size : mProduct.SizeList) {
				mSizeNameList.add(size.Size);
			}
			mAdapterSize.notifyDataSetChanged();
			mLayoutSize.setVisibility(View.VISIBLE);

		}
	}

	private void GetColor() {
		new CallServiceTask() {
			private ArrayList<Color>	rs	= new ArrayList<Color>();

			protected void onPreExecute() {
				mBtnBuy.setText(R.string.process);
				mBtnAdd.setText(R.string.process);
				isLoading = true;
			};

			public void work() {
				try {
					rs = service.getProductColor(mProduct.Id);
				} catch (IOException e) {} catch (XmlPullParserException e) {}
			};

			protected void onPostExecute(Void result) {
				mProduct.ColorList.addAll(rs);
				LoadColor();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void LoadColor() {
		if (mProduct.ColorList.size() != 0) {
			mColorNameList.clear();
			mColorList.clear();
			mColorList.addAll(mProduct.ColorList);
			mColorNameList.add("");
			for (Color color : mProduct.ColorList) {

				if (mContext.getLocale().equals(Locale.ENGLISH))
					mColorNameList.add(color.NameEN);
				else if (mContext.getLocale().equals(Locale.KOREA))
					mColorNameList.add(color.NameKR);
				else
					mColorNameList.add(color.NameVN);
			}
			mLayoutColor.setVisibility(View.VISIBLE);
			mAdapterColor.notifyDataSetChanged();
		}
	}

	private void checkQuantity() {
		if (mEdQuantity.getText().length() == 0) {
			mEdQuantity.setText("1");
		} else if (Integer.parseInt(mEdQuantity.getText().toString()) < 1) {
			mEdQuantity.setText("1");
		}
	}

	private void AddToCart(OrderDetail order) {
		for (OrderDetail detail : mContext.mOrder.ListDetail) {
			if (detail.ProductID == order.ProductID && detail.Size == order.Size && detail.Color == order.Color) {
				detail.Quantity = detail.Quantity + order.Quantity;
				return;
			}
		}

		mContext.mOrder.ListDetail.add(order);

	}

	@Override
	public void onClick(final View v) {
		switch (v.getId()) {
		case R.id.detail_btnAdd:
			if (isLoading) {
				new WarningDialog(mContext, mContext.getString(R.string.processwait)).show();
				return;
			}
			if (!isAdding) {
				if ((mLayoutColor.getVisibility() == View.VISIBLE && mSpinColor.getSelectedItemPosition() == 0)
						|| (mLayoutSize.getVisibility() == View.VISIBLE && mSpinSize.getSelectedItemPosition() == 0)) {
					new WarningDialog(mContext, mContext.getString(R.string.size_or_color_is_blank)).show();
					return;
				}
				isAdding = true;
				checkQuantity();
				if (mContext.mUser != null) {
					if (mLayoutColor.getVisibility() == View.VISIBLE)
						mProduct.Color = mColorList.get(mSpinColor.getSelectedItemPosition() - 1);
					if (mLayoutSize.getVisibility() == View.VISIBLE)
						mProduct.Size = mSizeList.get(mSpinSize.getSelectedItemPosition() - 1);
					mProduct.Quantity = Integer.parseInt(mEdQuantity.getText().toString());

					OrderDetail detail = new OrderDetail();
					detail.ProductID = mProduct.Id;
					detail.ProductName = mProduct.Name;
					detail.CategoryNameEN = mProduct.CategoryNameEN;
					detail.CategoryNameVN = mProduct.CategoryNameVN;
					detail.CategoryNameKR = mProduct.CategoryNameKR;
					detail.Price = mProduct.Price - mProduct.Price * mProduct.SaleOff / 100;
					detail.PriceVN = (mProduct.SaleOff != 0) ? mProduct.PriceSale : mProduct.PriceVN;
					if (mProduct.Color != null) {
						detail.ColorNameEN = mProduct.Color.NameEN;
						detail.ColorNameKR = mProduct.Color.NameKR;
						detail.ColorNameVN = mProduct.Color.NameVN;
						detail.Color = mProduct.Color.ColorID;
					} else {
						detail.Color = -1;
					}
					if (mProduct.Size != null) {
						detail.SizeName = mProduct.Size.Size;
						detail.Size = mProduct.Size.SizeID;
					} else {
						detail.Size = -1;
					}
					detail.Quantity = mProduct.Quantity;
					detail.Image = mProduct.Image;
					detail.SaleOff = mProduct.SaleOff;

					AddToCart(detail);
					Toast.makeText(mContext, mContext.getString(R.string.addsuccess), Toast.LENGTH_SHORT).show();
				} else {
					Intent i = new Intent(mContext, LoginActivity.class);
					mContext.startActivityForResult(i, MainActivity.LOGINACTIVITY);
				}
				isAdding = false;
			}

			break;
		case R.id.detail_btnBuy:
			v.setEnabled(false);
			if (isLoading) {
				new WarningDialog(mContext, mContext.getString(R.string.processwait)).show();
				v.setEnabled(true);
				return;
			}
			if ((mLayoutColor.getVisibility() == View.VISIBLE && mSpinColor.getSelectedItemPosition() == 0)
					|| (mLayoutSize.getVisibility() == View.VISIBLE && mSpinSize.getSelectedItemPosition() == 0)) {
				new WarningDialog(mContext, mContext.getString(R.string.size_or_color_is_blank)).show();
				v.setEnabled(true);
				return;
			}
			checkQuantity();
			if (mContext.mUser != null) {
				if (mLayoutColor.getVisibility() == View.VISIBLE)
					mProduct.Color = mColorList.get(mSpinColor.getSelectedItemPosition() - 1);
				if (mLayoutSize.getVisibility() == View.VISIBLE)
					mProduct.Size = mSizeList.get(mSpinSize.getSelectedItemPosition() - 1);
				mProduct.Quantity = Integer.parseInt(mEdQuantity.getText().toString());

				OrderDetail detail = new OrderDetail();
				detail.ProductID = mProduct.Id;
				detail.ProductName = mProduct.Name;
				detail.CategoryNameEN = mProduct.CategoryNameEN;
				detail.CategoryNameVN = mProduct.CategoryNameVN;
				detail.CategoryNameKR = mProduct.CategoryNameKR;
				detail.Price = mProduct.Price - mProduct.Price * mProduct.SaleOff / 100;
				detail.PriceVN = (mProduct.SaleOff != 0) ? mProduct.PriceSale : mProduct.PriceVN;
				if (mProduct.Color != null) {
					detail.CategoryNameEN = mProduct.CategoryNameEN;
					detail.CategoryNameVN = mProduct.CategoryNameVN;
					detail.CategoryNameKR = mProduct.CategoryNameKR;
					detail.Color = mProduct.Color.ColorID;
				} else {
					detail.Color = -1;
				}
				if (mProduct.Size != null) {
					detail.SizeName = mProduct.Size.Size;
					detail.Size = mProduct.Size.SizeID;
				} else {
					detail.Size = -1;
				}
				detail.Quantity = mProduct.Quantity;
				detail.Image = mProduct.Image;
				detail.SaleOff = mProduct.SaleOff;
				mContext.mBuyNowOrder = new Order();
				mContext.mBuyNowOrder.ListDetail.add(detail);

				ShippingDialog dialog = new ShippingDialog(mContext, true);
				dialog.setCancelable(true);
				dialog.show();
				dialog.setOnDismissListener(new OnDismissListener() {
					@Override
					public void onDismiss(DialogInterface dialog) {
						v.setEnabled(true);
					}
				});
			} else {
				Intent i = new Intent(mContext, LoginActivity.class);
				mContext.startActivityForResult(i, MainActivity.LOGINACTIVITY);
				v.setEnabled(true);
			}
			break;
		case R.id.detail_txtReview:

			break;
		}
	}
}
